package com.glory.brepda.activity.recipe;

import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.glory.brepda.R;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.base.Constant;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.LotInfoEntity;
import com.glory.brepda.entity.MarkNumPathEntity;
import com.glory.brepda.entity.UpdateIPEntity;
import com.glory.brepda.entity.request.BaseRequest;
import com.glory.brepda.entity.request.HeaderBean;
import com.glory.brepda.entity.request.RequestBean;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringEscapeUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.OkHttpClient;

public class SealDownSearchActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etEqpid)
    FreeUI_ClearEditText etEqpid;
    @BindView(R.id.tvEqpType)
    TextView tvEqpType;
    @BindView(R.id.tvEqpID)
    TextView tvEqpID;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.tvCustomer)
    TextView tvCustomer;
    @BindView(R.id.tvOrderNum)
    TextView tvOrderNum;
    @BindView(R.id.tvSealFile)
    TextView tvSealFile;
    @BindView(R.id.tvDownLoad)
    TextView tvDownLoad;
    @BindView(R.id.tvPrrType)
    TextView tvPrrType;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    LotInfoEntity lotInfoEntity;
    private String prrType;
    private String fileName;
    @Override
    protected int getLayoutResId() {
        return R.layout.activity_seal_down_search;
    }

    @Override
    protected void initView() {
        setMainLayout(llMain);
        tvBaseSubmit.setVisibility(View.GONE);
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);

        initEdit(etEqpid, s -> {
            if (getText(etLot).equals("")){
                showToast("请先扫描批次号",false);
                etEqpid.setText("");
                etLot.requestFocus();
                return;
            }

            FreeUI_EntityCallBack<BaseResponseBean<MarkNumPathEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<MarkNumPathEntity>>
                    (new TypeToken<BaseResponseBean<MarkNumPathEntity>>() {
                    }.getType(), getSupportFragmentManager(), this) {

                @Override
                public void onSuccess(Response<BaseResponseBean<MarkNumPathEntity>> response) {
                    super.onSuccess(response);
                    if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                        MarkNumPathEntity body = response.body().getResponse().getBody();
                        tvSealFile.setText(body.getMARKPATH());
                        tvEqpType.setText(body.getEQUIPMENTTYPE());
                        tvPrrType.setText(body.getPROGRAMTYPE());
                        tvEqpID.setText(body.getLSEQPID());
                        prrType = body.getMARKPATH();
                        fileName = body.getFILENAME();
//                        requestSealInfo(lotInfoEntity);
                    }
                }

                @Override
                public void onError(Response<BaseResponseBean<MarkNumPathEntity>> response) {
                    super.onError(response);
                    loadError(response.getException(), "GETEQPINFOBYEQPID");
                }
            };

            JsonObject map = new JsonObject();
            map.addProperty("LOTID",getText(etLot));
            map.addProperty("CUSTOMERORDER",lotInfoEntity.getLOT().getCUSTOMERCODE());
            map.addProperty("WOID",lotInfoEntity.getLOT().getWOID());
            map.addProperty("EQUIPMENTID",getText(etEqpid));

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
            loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
            loggingInterceptor.setColorLevel(java.util.logging.Level.INFO);
            builder.addInterceptor(loggingInterceptor);
            builder.connectTimeout(240 * 1000L, TimeUnit.MILLISECONDS);
            builder.readTimeout(240 * 1000L, TimeUnit.MILLISECONDS);
            builder.writeTimeout(240 * 1000L, TimeUnit.MILLISECONDS);
            OkGo okGo = OkGo.getInstance().init(getApplication());
            okGo.setOkHttpClient(builder.build()).setCacheMode(CacheMode.NO_CACHE).setCacheTime(-1L).setRetryCount(0);

            RequestBean requestBean = new RequestBean();
            requestBean.setHeader(new HeaderBean("IF.GetMarkNumPath"));
            requestBean.setBody(map);
            BaseRequest request = new BaseRequest();
            request.setRequest(requestBean);

            Map<String,String> map1 = new HashMap<>();

//        map.put("senderId","EAP2CPCSender");
            map1.put("requestMessage", StringEscapeUtils.unescapeJson(new Gson().toJson(request)));
            map1.put("timeOut","5000");

            FreeApi_LogUtils.saveErrorMessages("http://"+ Constant.REQUEST_URL_DEBUG+"/api/"+"GetMarkNumPath1","请求地址");
            FreeApi_LogUtils.saveErrorMessages(map.toString(),"请求json");

            ((PostRequest)((PostRequest)okGo.post("http://"+ Constant.REQUEST_URL_DEBUG+"/api/"+"GetMarkNumPath1").tag(this)).params(map1, new boolean[]{true})).execute(callBack);

//            NetUtils.requestPostNet("IF.GetMarkNumPath","GetMarkNumPath",this,map,callBack);

        });

        initEdit(etLot, s -> {

            LotUtils.searchLotInfo(SealDownSearchActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
                @Override
                public void onSuccess(LotInfoEntity response) {
                    lotInfoEntity = response;
                    tvCustomer.setText(response.getLOT().getCUSTOMERCODE());
                    tvOrderNum.setText(response.getLOT().getWOID());
                    etEqpid.setText("");
                    tvEqpID.setText("");
                    tvEqpType.setText("");
                    tvPrrType.setText("");
                    tvSealFile.setText("");
                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t,"LOTQUERY");
                }
            });

        });
    }

    private void requestSealInfo(LotInfoEntity response) {
        FreeUI_EntityCallBack<BaseResponseBean<UpdateIPEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<UpdateIPEntity>>
                (new TypeToken<BaseResponseBean<UpdateIPEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<UpdateIPEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    tvSealFile.setText(response.body().getResponse().getBody().getMARKPATH());
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<UpdateIPEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"GetEqpMarkNumPath");
            }
        };

    }

    @Override
    protected void initData() {

    }

    @OnClick(R.id.tvDownLoad)
    public void onViewClicked() {
//        if (actionControl("DownLoad05")) {
//            return;
//        }

        if (getText(etLot).equals("") || getText(etEqpid).equals("")){
            showToast("请先扫描批次号或设备号",false);
            return;
        }else if (tvOrderNum.getText().toString().equals("") || tvEqpType.getText().toString().equals("")) {
            showToast("信息不全，请扫描正确的批次号及设备号", false);
        }else{
            FreeUI_EntityCallBack<BaseResponseBean<UpdateIPEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<UpdateIPEntity>>
                    (new TypeToken<BaseResponseBean<UpdateIPEntity>>() {
                    }.getType(), getSupportFragmentManager(), this) {

                @Override
                public void onSuccess(Response<BaseResponseBean<UpdateIPEntity>> response) {
                    super.onSuccess(response);
                    if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                        showConfirmDialog(SealDownSearchActivity.this,"调用成功!");
                    }

                }

                @Override
                public void onError(Response<BaseResponseBean<UpdateIPEntity>> response) {
                    super.onError(response);
                    loadError(response.getException(),"SendEqpMarkNum");
                }
            };

            JsonObject map = new JsonObject();
            map.addProperty("EQPID",tvEqpID.getText().toString());
            map.addProperty("LOTNO",getText(etLot));
            map.addProperty("WOID",tvOrderNum.getText().toString());
            map.addProperty("CUSTOMER",tvCustomer.getText().toString());
            map.addProperty("FILEPATH",prrType.replaceAll("\\\\","\\\\\\\\"));
            map.addProperty("FTEQPID",getText(etEqpid));
            map.addProperty("FILENAME",fileName);
            NetUtils.requestPostNet("IF.SendEqpMarkNum","SendEqpMarkNum",SealDownSearchActivity.this,map,callBack);
        }
    }
}